package com.haifeng.lyw.blerobot;

import android.app.ProgressDialog;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.haifeng.lyw.blerobot.custom.DragViewCtr;
import com.haifeng.lyw.blerobot.dialog.ChassisDialog;
import com.haifeng.lyw.blerobot.service.BluetoothLeService;
import com.haifeng.lyw.blerobot.utils.BleInfo;
import com.haifeng.lyw.blerobot.utils.L;
import com.haifeng.lyw.blerobot.utils.NavController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener, NavController.OnNavAndSpeedListener {


    private String TAG = "ActionActivity";
    //显示连接状态
    TextView mConnectState;
    //自定义悬浮按钮
//    private DragViewCtr ctr = null;
    //加载dialog
    private ProgressDialog progressDialog;

    //蓝牙连接状态
    private boolean mConnected = false;
    private String status = "disconnected";
    //蓝牙名字
    private String mDeviceName;
    //蓝牙地址
    private String mDeviceAddress;
    //蓝牙信号值
    private String mRssi;
    private Bundle b;
    private String rev_str = "";
    //蓝牙service,负责后台的蓝牙服务
    private static BluetoothLeService mBluetoothLeService;

    private ArrayList<ArrayList<BluetoothGattCharacteristic>> mGattCharacteristics = new ArrayList<>();
    //蓝牙特征值
    private static BluetoothGattCharacteristic target_chara = null;
    private Handler mhandler = new Handler();
    private Handler myHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    if (progressDialog != null && progressDialog.isShowing())
                        progressDialog.dismiss();
                    if (mConnected) {
                        //连接成功
                        setEnabled(true);
                    } else {
                        //连接失败
                        setEnabled(false);
                        mCounterGuard.setEnabled(false);
                    }
                    String state = msg.getData().getString("connect_state");
                    mConnectState.setText(state);
                    break;
            }
            super.handleMessage(msg);
        }
    };

    private ToggleButton
            //mFront,mBack,mLeft,mRight,mLeftFront,mLeftBack,mRightFront,mRightBack,
            mCounterGuard;

    //标识 壁障前行
    private boolean isCounterGuard = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        fullScreen();
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fang);
        b = getIntent().getExtras();
        //从意图获取显示的蓝牙信息
        mDeviceName = b.getString(BleInfo.EXTRAS_DEVICE_NAME);
        mDeviceAddress = b.getString(BleInfo.EXTRAS_DEVICE_ADDRESS);
        mRssi = b.getString(BleInfo.EXTRAS_DEVICE_RSSI);

		/* 启动蓝牙service */
        Intent gattServiceIntent = new Intent(this, BluetoothLeService.class);
        bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
        NavController navController= (NavController) findViewById(R.id.nav_control);
        navController.setOnNavAndSpeedListener(this);
        initView();
    }

    // Activity出来时候，绑定广播接收器，监听蓝牙连接服务传过来的事件
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    @Override
    protected void onResume() {
        super.onResume();
        /*if (ctr == null) {
            ctr = new DragViewCtr(this);
            ctr.showDragCallView();
            ctr.setOnClickListener(dragClickListener);
        }*/

        if (!mConnected) {
            //显示ProgressDialog
            progressDialog = ProgressDialog.show(this, "", "正在尝试连接蓝牙", true, false);
            //绑定广播接收器
            registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
            if (mBluetoothLeService != null) {
                //根据蓝牙地址，建立连接
                final boolean result = mBluetoothLeService.connect(mDeviceAddress);
                Log.d(TAG, "Connect request result=" + result);
                if (!result)
                    if (progressDialog != null && progressDialog.isShowing())
                        progressDialog.dismiss();
            }
        }
    }

    private ChassisDialog mChassisDialog = null;

    DragViewCtr.OnClickListener dragClickListener = new DragViewCtr.OnClickListener() {
        @Override
        public void onClick() {
            /*if (ctr != null)
                ctr.setCanDrag(false);*/
            //显示自定义Dialog
            if (mChassisDialog == null) {
                mChassisDialog = new ChassisDialog(MainActivity.this, "底盘、前后臂运动控制", -1);
            }
            if (!mChassisDialog.isShowing()) {
                mChassisDialog.show();
                mChassisDialog.setClicklistener(new ChassisDialog.ClickListenerInterface() {
                    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
                    @Override
                    public void send(int id, boolean action) {
                        //sendOrder(id, action);
                    }

                    @Override
                    public void dissmis() {
                       /* if (ctr != null)
                            ctr.setCanDrag(true);*/
                        fullScreen();
                    }
                });
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        L.e("www", "onDestroy");
        //解除广播接收器
        unregisterReceiver(mGattUpdateReceiver);
        mBluetoothLeService = null;
    }

    /**
     * 初始化数据
     */
    private void initView() {
        mConnectState = (TextView) findViewById(R.id.connect_state);

        mCounterGuard = (ToggleButton) findViewById(R.id.fang_counter_guard);

        mCounterGuard.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
                String code;
                if(isChecked){
                    code = "5";

                }else {
                    code = "0";
                }
                if (!TextUtils.isEmpty(code))
                    sendByBle(code);
            }
        });
        setEnabled(true);
    }

    private void setEnabled(boolean enabled) {
//        mFront.setEnabled(enabled);
//        mBack.setEnabled(enabled);
//        mLeft.setEnabled(enabled);
//        mRight.setEnabled(enabled);
//        mLeftFront.setEnabled(enabled);
//        mLeftBack.setEnabled(enabled);
//        mRightFront.setEnabled(enabled);
//        mRightBack.setEnabled(enabled);
        mCounterGuard.setEnabled(enabled);
    }

    /* BluetoothLeService绑定的回调函数 */
    private final ServiceConnection mServiceConnection = new ServiceConnection() {

        @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder service) {
            mBluetoothLeService = ((BluetoothLeService.LocalBinder) service)
                    .getService();
            if (!mBluetoothLeService.initialize()) {
                L.e(TAG, "Unable to initialize Bluetooth");
                finish();
            }
            // Automatically connects to the device upon successful start-up
            // initialization.
            // 根据蓝牙地址，连接设备
            mBluetoothLeService.connect(mDeviceAddress);

        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mBluetoothLeService = null;
        }

    };

    /**
     * 广播接收器，负责接收BluetoothLeService类发送的数据
     */
    private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
        @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {//Gatt连接成功
                mConnected = true;
                status = "已连接";
                //更新连接状态
                updateConnectionState(status);
                System.out.println("BroadcastReceiver :" + "device connected");

            } else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {//Gatt连接失败
                mConnected = false;
                status = "连接失败";
                //更新连接状态
                updateConnectionState(status);
                System.out.println("BroadcastReceiver :"
                        + "device disconnected");

            } else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {//发现GATT服务器
                // Show all the supported services and characteristics on the
                // user interface.
                //获取设备的所有蓝牙服务
                displayGattServices(mBluetoothLeService.getSupportedGattServices());
                System.out.println("BroadcastReceiver :device SERVICES_DISCOVERED");
            } else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {//有效数据
                //处理发送过来的数据
                displayData(intent.getExtras().getString(BluetoothLeService.EXTRA_DATA));
                System.out.println("BroadcastReceiver onData:"
                        + intent.getStringExtra(BluetoothLeService.EXTRA_DATA));
            }
        }
    };

    /* 更新连接状态 */
    private void updateConnectionState(String status) {
        Message msg = new Message();
        msg.what = 1;
        Bundle b = new Bundle();
        b.putString("connect_state", status);
        msg.setData(b);
        //将连接状态更新的UI的textview上
        myHandler.sendMessage(msg);
        System.out.println("connect_state:" + status);

    }

    /* 意图过滤器 */
    private static IntentFilter makeGattUpdateIntentFilter() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED);
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED);
        intentFilter
                .addAction(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED);
        intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE);
        return intentFilter;
    }

    /**
     * @param @param rev_string(接受的数据)
     * @return void
     * @throws
     * @Title: displayData
     * @Description: TODO(接收到的数据在scrollview上显示)
     */
    private void displayData(String rev_string) {
        rev_str += rev_string;
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
//                rev_tv.setText(rev_str);
//                rev_sv.scrollTo(0, rev_tv.getMeasuredHeight());
                System.out.println("rev:" + rev_str);
            }
        });
    }

    /**
     * @param
     * @return void
     * @throws
     * @Title: displayGattServices
     * @Description: TODO(处理蓝牙服务)
     */
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    private void displayGattServices(List<BluetoothGattService> gattServices) {

        if (gattServices == null)
            return;
        String uuid = null;
        String unknownServiceString = "unknown_service";
        String unknownCharaString = "unknown_characteristic";

        // 服务数据,可扩展下拉列表的第一级数据
        ArrayList<HashMap<String, String>> gattServiceData = new ArrayList<HashMap<String, String>>();

        // 特征数据（隶属于某一级服务下面的特征值集合）
        ArrayList<ArrayList<HashMap<String, String>>> gattCharacteristicData = new ArrayList<ArrayList<HashMap<String, String>>>();

        // 部分层次，所有特征值集合
        mGattCharacteristics = new ArrayList<ArrayList<BluetoothGattCharacteristic>>();

        // Loops through available GATT Services.
        for (BluetoothGattService gattService : gattServices) {

            // 获取服务列表
            HashMap<String, String> currentServiceData = new HashMap<String, String>();
            uuid = gattService.getUuid().toString();

            // 查表，根据该uuid获取对应的服务名称。SampleGattAttributes这个表需要自定义。

            gattServiceData.add(currentServiceData);

            System.out.println("Service uuid:" + uuid);

            ArrayList<HashMap<String, String>> gattCharacteristicGroupData = new ArrayList<HashMap<String, String>>();

            // 从当前循环所指向的服务中读取特征值列表
            List<BluetoothGattCharacteristic> gattCharacteristics = gattService
                    .getCharacteristics();

            ArrayList<BluetoothGattCharacteristic> charas = new ArrayList<BluetoothGattCharacteristic>();

            // Loops through available Characteristics.
            // 对于当前循环所指向的服务中的每一个特征值
            for (final BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
                charas.add(gattCharacteristic);
                HashMap<String, String> currentCharaData = new HashMap<String, String>();
                uuid = gattCharacteristic.getUuid().toString();

                if (gattCharacteristic.getUuid().toString()
                        .equals(BleInfo.HEART_RATE_MEASUREMENT)) {
                    // 测试读取当前Characteristic数据，会触发mOnDataAvailable.onCharacteristicRead()
                    mhandler.postDelayed(new Runnable() {

                        @Override
                        public void run() {
                            // TODO Auto-generated method stub
                            mBluetoothLeService
                                    .readCharacteristic(gattCharacteristic);
                        }
                    }, 200);

                    // 接受Characteristic被写的通知,收到蓝牙模块的数据后会触发mOnDataAvailable.onCharacteristicWrite()
                    mBluetoothLeService.setCharacteristicNotification(
                            gattCharacteristic, true);
                    target_chara = gattCharacteristic;
                    // 设置数据内容
                    // 往蓝牙模块写入数据
                    // mBluetoothLeService.writeCharacteristic(gattCharacteristic);
                }
                List<BluetoothGattDescriptor> descriptors = gattCharacteristic
                        .getDescriptors();
                for (BluetoothGattDescriptor descriptor : descriptors) {
                    System.out.println("---descriptor UUID:"
                            + descriptor.getUuid());
                    // 获取特征值的描述
                    mBluetoothLeService.getCharacteristicDescriptor(descriptor);
                    // mBluetoothLeService.setCharacteristicNotification(gattCharacteristic,
                    // true);
                }

                gattCharacteristicGroupData.add(currentCharaData);
            }
            // 按先后顺序，分层次放入特征值集合中，只有特征值
            mGattCharacteristics.add(charas);
            // 构件第二级扩展列表（服务下面的特征值）
            gattCharacteristicData.add(gattCharacteristicGroupData);

        }

    }


    /**
     * 设置全屏
     */
    public void fullScreen() {
        int uiFlags = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
                | View.SYSTEM_UI_FLAG_FULLSCREEN; // hide status bar

        if (Build.VERSION.SDK_INT >= 19) {
            uiFlags |= 0x00001000;    //SYSTEM_UI_FLAG_IMMERSIVE_STICKY: hide navigation bars - compatibility: building API level is lower thatn 19, use magic number directly for higher API target level
        } else {
            uiFlags |= View.SYSTEM_UI_FLAG_LOW_PROFILE;
        }

        getWindow().getDecorView().setSystemUiVisibility(uiFlags);
    }



    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    private void sendByBle(String send_et) {
        L.i("WWDZ", "sendByBle-->" + send_et);
        if (TextUtils.isEmpty(send_et))
            return;

        byte[] buff = send_et.getBytes();
        int len = buff.length;
        int[] lens = dataSeparate(len);
        for (int i = 0; i < lens[0]; i++) {
            String str = new String(buff, 20 * i, 20);
            target_chara.setValue(str);//只能一次发送20字节，所以这里要分包发送
            //调用蓝牙服务的写特征值方法实现发送数据
            mBluetoothLeService.writeCharacteristic(target_chara);
        }
        if (lens[1] != 0) {
            String str = new String(buff, 20 * lens[0], lens[1]);
            Log.i("WWDZ",str);
            try{
                target_chara.setValue(str);
                //调用蓝牙服务的写特征值方法实现发送数据
                mBluetoothLeService.writeCharacteristic(target_chara);
            }catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

    /**
     * 将数据分包
     **/
    public int[] dataSeparate(int len) {
        int[] lens = new int[2];
        lens[0] = len / 20;
        lens[1] = len - 20 * lens[0];
        return lens;
    }


    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.fang_counter_guard:
                //壁障前行
                String code;
                if (isCounterGuard) {
                    //停止
                    code = "5";
                    mCounterGuard.setText("壁障前行(开)");
                } else {
                    //开启
                    code = "0";
                    mCounterGuard.setText("壁障前行(关)");
                }

                if (!TextUtils.isEmpty(code))
                    sendByBle(code);

                isCounterGuard = !isCounterGuard;
                setEnabled(!isCounterGuard);

                break;
        }
    }

    @Override
    public void onNavAndSpeed(int nav) {
        String code = "";
        if (nav == 5) {
            code = "6";//右

        } else if (nav == 4) {
            code = "9";//右下
        }else if (nav == 3) {
            code = "8";//下
        }else if (nav == 6) {
            code = "3";//右上
        }else if (nav == 7) {
            code = "2";//上
        }else if (nav == 1) {
            code = "4";//左
        }else if (nav == 2) {
            code = "7";//左下
        }else if (nav == 0) {
            code = "1";//左上
        }else {
            code = "5";//停
        }
        if (!TextUtils.isEmpty(code))
            sendByBle(code);

    }
}

